/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */

package com.ecarx.systemui.plugin.model

import android.car.hardware.property.CarPropertyManager.CarPropertyEventCallback
import android.car.hardware.property.CarPropertyManager.SENSOR_RATE_NORMAL
import com.ecarx.systemui.plugin.utils.LogUtils

abstract class BasePropertyImpl<T> : BaseModel(), IBaseProperty<T> {

    abstract val TAG: String

    override suspend fun isAvailable(area: Int): Boolean {
        waitUntilReady()
        val available = carPropertyManager.isPropertyAvailable(mPropertyId, area)
        LogUtils.d(TAG, "isAvailable:$available area:$area property:$mPropertyId")
        return available
    }

    override suspend fun getValue(area: Int): T {
        waitUntilReady()
        val value = carPropertyManager.getProperty<T>(mPropertyId, area)
        LogUtils.d(TAG, "getValue : $value  area:$area property:$mPropertyId")
        return value.value
    }

    override suspend fun <T> setValue(value: T, area: Int) {
        LogUtils.d(TAG, "setValue : $value  area: $area property:$mPropertyId")
        if (!isAvailable(area)) {
            return
        }
        when (value) {
            is Int -> {
                carPropertyManager.setIntProperty(mPropertyId, area, value)
            }
            is Boolean -> {
                carPropertyManager.setBooleanProperty(mPropertyId, area, value)
            }
            is Float -> {
                carPropertyManager.setFloatProperty(mPropertyId, area, value)
            }
            else -> {
                throw java.lang.IllegalArgumentException("not support value type")
            }
        }
    }

    override suspend fun registerCallback(callback: CarPropertyEventCallback) {
        LogUtils.d(TAG, "registerCallback:$callback mPropertyId:$mPropertyId")
        waitUntilReady()
        carPropertyManager.registerCallback(callback, mPropertyId, SENSOR_RATE_NORMAL)
    }

    override suspend fun unRegisterCallback(callback: CarPropertyEventCallback) {
        LogUtils.d(TAG, "unRegisterCallback$callback")
        waitUntilReady()
        carPropertyManager.unregisterCallback(callback)
    }
}